<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // 尾递归是递归的一种
        // 递归过多容易造成栈溢出

        // 1 实现阶乘--下面是普通递归--法，就容易造成栈溢出，复杂度为 O(n)
        function factorial(n){
            if(n === 1) return 1
            return n * factorial(n-1)
        }
        const fainal = factorial(5)
        console.log('fainal',fainal);

        function factorial2(n,total){
            if(n === 1) return total
            return factorial2(n-1,n * total)
        }
        const fainal2 = factorial2(5,1)
        console.log('fainal2',fainal2);


        // 数组扁平化
        let a = [1,2,3, [1,2,3, [1,2,3]]]
        function flat(arr = [], result = []){
            arr.forEach(v=>{
                if(Array.isArray(v)){
                    result =  result.concat(flat(v,[]))
                }else{
                    result.push(v)
                }
            })
            return result
        }
        const r = flat(a)
        console.log('r',r)
    </script>
</body>
</html>